package com.lock;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author yijy
 * @description
 * @create 2021/4/1 下午8:45
 **/
public class SynchronizedTest {

    static long count= 0;
    static AtomicLong count1 = new AtomicLong(0);
    static LongAdder longAdder = new LongAdder();
    static int limit = 100;

    public static void main(String[] args) throws InterruptedException {
        Thread[] synThreadArr = new Thread[10];
        for(int i=0; i < synThreadArr.length ; i++){
            synThreadArr[i] = new Thread(()->{
                for (int j=0;j < limit; j ++){
                    count1.incrementAndGet();
                }
            });
        }
        long start = System.currentTimeMillis();
        for (Thread r : synThreadArr) r.start();
        for (Thread r : synThreadArr) r.join();
        System.out.println("atomicLong value = "+count1.intValue()+" ; atomicLong耗时: "+ (System.currentTimeMillis() - start));
        Object lock = new Object();
        for(int i=0; i < synThreadArr.length ; i++){
            synThreadArr[i] = new Thread(()->{
                for (int j=0;j < limit; j ++){
                    synchronized (lock) {
                        count ++;
                    }
                }
            });
        }
        long start1 = System.currentTimeMillis();
        for (Thread r : synThreadArr) r.start();
        for (Thread r : synThreadArr) r.join();
        System.out.println("sync value = "+count+" ; sync耗时: "+ (System.currentTimeMillis() - start1));

        for(int i=0; i < synThreadArr.length ; i++){
            synThreadArr[i] = new Thread(()->{
                for (int j=0;j < limit; j ++){
                    longAdder.increment();
                }
            });
        }
        long start2 = System.currentTimeMillis();
        for (Thread r : synThreadArr) r.start();
        for (Thread r : synThreadArr) r.join();
        System.out.println("longAddr value = "+longAdder.intValue()+"; longAddr耗时: "+ (System.currentTimeMillis() - start2));

    }
}
